/*
 * Copyright (c) 2010, okazoh_tk. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 *  - Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *  - Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *  - Neither the name of the copyright holder nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "alkes/tree/GraphicsContext.h"
#include "alkes/tree/UpdateContext.h"
#include "alkes/tree/Screen.h"
#include "alkes/tree/Layer.h"

namespace alkes {

Screen::Screen()
{
}

Screen::~Screen()
{
    Layer* layer;
    while (0 != (layer = static_cast<Layer*>(layer_list_.shift())))
    {
        removeLayer(layer);
        delete layer;
    }
}

bool Screen::initialize()
{
    return onCreate();
}

void Screen::finalize()
{
    onDestroy();
}

void Screen::setClearColor(const Color& color)
{
    clear_color_ = color;
}

const Color& Screen::getClearColor() const
{
    return clear_color_;
}

Layer* Screen::registerLayer()
{
    Layer* layer = new Layer(getContext());

    if (registerLayer(layer))
    {
        addLayer(layer);
    }
    else
    {
        delete layer;
        layer = 0;
    }

    return layer;
}

bool Screen::registerLayer(Layer* layer)
{
    return layer_list_.push(layer);
}

bool Screen::addLayer(Layer* layer)
{
    return container_.push(layer);
}

void Screen::removeLayer(Layer* layer)
{
    container_.remove(layer);

    if (layer_list_.remove(layer))
    {
        delete layer;
    }
}

bool Screen::update()
{
    bool ret = onUpdate();

    if (!ret)
        return ret;

    bool updated = false;
    ElementContainer::Iterator iter = layer_list_.getFirst();
    while (iter)
    {
        updated = iter_cast<Layer*>(iter)->update() || updated;
        iter = iter->getNext();
    }

    return updated;
}

void Screen::render(const Rect* dirty_rect)
{
    Context* default_context = getContext();

    UpdateContext* uc;
    GraphicsContext* gc;

    if (!default_context
        || (0 == (uc = default_context->getUpdateContext()))
        || (0 == (gc = default_context->getGraphicsContext())))
    {
        //AL_DBG("Invalid state");
        return ;
    }

    //AL_DBG("Begin Screen::render()");

    if (dirty_rect)
        uc->addDirtyRect(*dirty_rect);

    bool render_default_context = false;
    {
        uint16_t dirty_count;
        const Rect* dirty_rects = uc->getMergedRects(dirty_count);
        if (dirty_rects && dirty_count)
        {
            // erase background
            onEraseBackground(dirty_rects, dirty_count, clear_color_);
            render_default_context = true;
        }
        else
        {
            //AL_DBG("Skip render.");
            return ;
        }
    }

    ElementContainer::Iterator iter = layer_list_.getFirst();
    Layer* layer;
    while (iter)
    {
        layer = iter_cast<Layer*>(iter);
        if (render_default_context
            || layer->getContext() != default_context)
        {
            layer->render();
        }
        iter = iter->getNext();
    }

    //gc->getRenderTarget2D()->setAlphaBlendEnable(false);
    //gc->getRenderTarget2D()->setAlphaBlendMode(true, AL_BLEND_ONE);
    //gc->getRenderTarget2D()->setAlphaBlendMode(false, AL_BLEND_ZERO);

    default_context->getGraphics()->flip();

    uc->resetDirtyRect();
    //AL_DBG("End Screen::render()");
}

bool Screen::onCreate()
{
    return true;
}

void Screen::onDestroy()
{
}

bool Screen::onUpdate()
{
    return true;
}

}
